package it.secse.idmadaption.credential;

import it.secse.idmadaption.exception.UnsopportedCredentialTypeException;
import it.secse.idmadaption.util.Constants;

import java.io.File;
import java.util.Iterator;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.om.impl.llom.OMElementImpl;
import org.apache.axis2.client.Options;
import org.apache.commons.httpclient.UsernamePasswordCredentials;

import org.tempuri.CredentialProviderServiceStub;
import org.tempuri.CredentialProviderServiceStub.AliasDelegatee_type0;
import org.tempuri.CredentialProviderServiceStub.DelegateeWrapperType;
import org.tempuri.CredentialProviderServiceStub.DelegateeWrapperTypeChoice_type0;
import org.tempuri.CredentialProviderServiceStub.GetSecurityTokenForDelegatee;
import org.tempuri.CredentialProviderServiceStub.GetSecurityTokenForDelegateeResponse;
import org.tempuri.CredentialProviderServiceStub.SecurityTokenWrapperType;

public class DFWrapper {

	public static CredentialData getCredential(String serviceAddress,
			String delegator, String callbackAddress) throws UnsopportedCredentialTypeException {

		
		String delegationType = Constants.EMPTY_PASSWORD;
		CredentialData data = null;


		try {

			StAXOMBuilder builder = new StAXOMBuilder(Constants.DEFAULT_DIR
					+ File.separator + Constants.DELEGATEE_CREDENTIAL
					+ Constants.XML_EXTENSION);
			OMElement credentialDocument = builder.getDocumentElement();
			Iterator it1 = credentialDocument.getChildElements();
			while (it1.hasNext()) {
				OMElement credentialElement = (OMElement) it1.next();
				if (credentialElement.getLocalName().equals("credential")) {
					OMElement service = (OMElement) credentialElement
							.getFirstElement();
					if (service.getLocalName().equals("service"))
						if (service.getText().trim().equals(serviceAddress)) {
							OMElement credential = credentialElement.getFirstChildWithName(new QName(Constants.USR_PASS_CREDENTIAL));
								if (credential!=null) {									
									data = new UsrPassCredentialData();
									data.setType(Constants.USR_PASS_CREDENTIAL);
									OMElement username = credential.getFirstChildWithName(new QName("username"));
									((UsrPassCredentialData) data).setUserName(username.getText().trim());
									OMElement password = credential.getFirstChildWithName(new QName("password"));
									if (password!=null) {
										delegationType = Constants.PASSWORD_FROM_LOCAL;
										((UsrPassCredentialData) data).setPassword(password.getText().trim());
										
									}

								}
								else  // insert here managing for new credential
									throw new UnsopportedCredentialTypeException();
								
								
						}

				}
			}
			

			CredentialProviderServiceStub client = new CredentialProviderServiceStub();

			Options opts = client._getServiceClient().getOptions();
			opts.setTimeOutInMilliSeconds(300000);

			// create security token request & set callback data
			GetSecurityTokenForDelegatee token = new CredentialProviderServiceStub.GetSecurityTokenForDelegatee();
			token.setCallbackAddress(callbackAddress);

			// Patch for Google Wrapper
			 if (serviceAddress.endsWith("GoogleWrapper"))
			 serviceAddress = "http://schemas.google.com/gCal/2005#editor";
			// End patch

			token.setServiceAddress(serviceAddress);
			DelegateeWrapperType delegatee = new DelegateeWrapperType();
			DelegateeWrapperTypeChoice_type0 choice = new DelegateeWrapperTypeChoice_type0();
			AliasDelegatee_type0 alias = new AliasDelegatee_type0();
			alias.setAlias(((UsrPassCredentialData) data).getUserName());
			choice.setAliasDelegatee(alias);
			delegatee.setDelegateeWrapperTypeChoice_type0(choice);
			token.setDelegatee(delegatee);
			token.setDelegator(delegator);

			// Credential Provider Service
			GetSecurityTokenForDelegateeResponse response = client
					.GetSecurityTokenForDelegatee(token);
			SecurityTokenWrapperType responseToken = response
					.getGetSecurityTokenForDelegateeResult();
			System.out.println(responseToken.getClass().getName());

			// System.out.println(us.getUsername());

			return data;

		} catch (java.lang.Exception e) {
			System.err.println("DELEGA GIA IN ESSERE");
		}

		return data;
	}

}
